package life.xjw.community.provider;

import life.xjw.community.dto.AccessTokenDTO;
import life.xjw.community.dto.GiteeUser;
import okhttp3.*;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import java.io.IOException;

@Component
public class GiteeProvider {
    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(mediaType,JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                    .url("https://gitee.com/oauth/token?grant_type=authorization_code&code="+accessTokenDTO.getCode()+"&client_id="+accessTokenDTO.getClient_id()+"&redirect_uri="+accessTokenDTO.getRedirect_uri()+"&client_secret="+accessTokenDTO.getClient_secret())
                    .post(body)
                    .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            String token = string.split(":")[1].split("\"")[1];
            //System.out.println(token);
            return token;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
       public GiteeUser getUser(String accessToken)  {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                    .build();
           System.out.println(accessToken);
            try {
                Response response = client.newCall(request).execute();
                String string = response.body().string();
                GiteeUser giteeUser = JSON.parseObject(string,GiteeUser.class);
                return giteeUser;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

}
